package com.qidian.blog.service.impl;

import com.qidian.blog.factory.MapperFactory;
import com.qidian.blog.mapper.BlogArticleMapper;
import com.qidian.blog.mapper.BlogCategoryMapper;
import com.qidian.blog.pojo.BlogArticle;
import com.qidian.blog.pojo.BlogCategory;
import com.qidian.blog.service.IndexService;
import com.qidian.blog.util.JSONTools;
import com.qidian.blog.util.JudgeTools;
import com.qidian.blog.util.RedisTool;
import com.qidian.blog.util.pojo.QDResult;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author 郭浩
 * @Date 2022/10/13 10:26
 */
public class IndexServiceImpl implements IndexService {
    private BlogCategoryMapper categoryMapper = MapperFactory.getMapper(BlogCategoryMapper.class);
    private BlogArticleMapper articleMapper = MapperFactory.getMapper(BlogArticleMapper.class);
    @Override
    public QDResult load() {
        Jedis jedis = RedisTool.getResource();
        Map data = new HashMap();
        List<BlogCategory> cats = null;
        String catsKey = "CAT_9527";
        String catsJson = jedis.get(catsKey);
        if (JudgeTools.isNull(catsJson)){
            //redis无数据
            cats = categoryMapper.queryAll();
            jedis.set(catsKey, JSONTools.object2json(cats));
            jedis.expire(catsKey,60*30+(new Random().nextInt(60*30)));
        }else{
            cats = JSONTools.json2List(catsJson,BlogCategory.class);
        }
        data.put("categorys",cats);

        String articleKey = "ARTICLE_9527";
        String articleJson = jedis.get(articleKey);
        List<BlogArticle> articles = null;
        if (JudgeTools.isNull(articleJson)){
            articles = articleMapper.queryByPage(0,15,null,null,null);
            jedis.set(articleKey,JSONTools.object2json(articles));
            jedis.expire(articleKey,60*30+(new Random().nextInt(60*30)));
        }else{
            articles = JSONTools.json2List(articleJson,BlogArticle.class);
        }
        data.put("articles",articles);

        Map catAndArticle = new HashMap();
        for (BlogCategory cat : cats){
            BlogArticle article = new BlogArticle();
            article.setCategory(cat);
            String artsKey = "ARTICLE_BY_CATID" + cat.getCategoryId();
            String artsJson = jedis.get(artsKey);
            List<BlogArticle> arts = null;
            if (JudgeTools.isNull(artsJson)){
                arts = articleMapper.queryByPage(0,5,article,null,null);
                jedis.set(artsKey,JSONTools.object2json(arts));
                jedis.expire(artsKey,60*30+(new Random().nextInt(60 * 30)));
            }else {
                arts = JSONTools.json2List(artsJson,BlogArticle.class);
            }
            catAndArticle.put(cat.getCategoryName(),arts);
        }
        data.put("catArticles",catAndArticle);
        jedis.close();
        return QDResult.ok(data);
    }
}
